package com.sctvcloud.renhe.ui.activities;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.content.ContextCompat;
import android.support.v4.util.ArrayMap;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.PictureFileUtils;
import com.ruihang.generalibrary.ui.dialog.AlertDialogFragment;
import com.ruihang.generalibrary.ui.dialog.BaseDialogFragment;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.ListUtils;
import com.sctvcloud.renhe.R;
import com.sctvcloud.renhe.application.Constances;
import com.sctvcloud.renhe.base.BaseActivity;
import com.sctvcloud.renhe.beans.FUsers;
import com.sctvcloud.renhe.beans.SingleResult;
import com.sctvcloud.renhe.beans.ThirdUser;
import com.sctvcloud.renhe.http.AbsNetCallBack;
import com.sctvcloud.renhe.http.DMethods;
import com.sctvcloud.renhe.http.NetUtils;
import com.sctvcloud.renhe.http.ParamsEditor;
import com.sctvcloud.renhe.ui.dialog.AlertEditDialogFragment;
import com.sctvcloud.renhe.ui.dialog.ConfirmUnregFragment;
import com.sctvcloud.renhe.ui.dialog.PicChoiceDiaFragment;
import com.sctvcloud.renhe.ui.dialog.ShowDiaFragment;
import com.sctvcloud.renhe.ui.utils.GlideCircleTransform;
import com.sctvcloud.renhe.ui.utils.GlideUtil;
import com.sctvcloud.renhe.ui.utils.SkipUtil;
import com.sctvcloud.renhe.ui.utils.TitleUtils;
import com.sctvcloud.renhe.utils.UserManager;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import cn.sharesdk.framework.PlatformDb;
import cn.sharesdk.framework.ShareSDK;
import cn.sharesdk.sina.weibo.SinaWeibo;
import cn.sharesdk.tencent.qq.QQ;
import cn.sharesdk.wechat.friends.Wechat;
import retrofit2.Call;

/**
 * Created by raoweiwei on 2017/8/2.
 * 用户信息页
 */

public class UserInfoActivity extends BaseActivity implements View.OnClickListener, AlertEditDialogFragment.OnViewClick, PicChoiceDiaFragment
        .ICallBack {
    @BindView(R.id.iv_user_img)
    protected CustomEXImageView mIvUserImg;
    @BindView(R.id.btn_change_img)
    protected CustomFontTextView mBtnChangeImg;
    @BindView(R.id.btn_change_name)
    protected CustomFontTextView mTvName;
    @BindView(R.id.btn_bind_weixin)
    protected CustomFontTextView mBtnBindWeixin;
    @BindView(R.id.btn_bind_qq)
    protected CustomFontTextView mBtnBindQQ;
    @BindView(R.id.btn_bind_weibo)
    protected CustomFontTextView mBtnBindWeibo;
    @BindView(R.id.btn_unreg)
    protected CustomFontTextView btn_unreg;

    private AlertEditDialogFragment mChangeNameDialog;
    private PicChoiceDiaFragment mPicChoice;
    private AlertDialogFragment unbindDialog;

    private int openType;
    /**
     * 第三方绑定点击后的view缓存,
     */
    private CustomFontTextView thirdClickTemp;
    /**
     * 是否正在更改用户名
     */
    private boolean isChangeNameing;
    /**
     * 是否正在更改图片
     */
    private boolean isChangeImg;

    private Call<?> imgCall;

    private GlideCircleTransform circleTransform;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        handler = new Handler();
        new TitleUtils(this).useAndSetTxTitle("账号信息");

        FUsers fUsers = UserManager.getInstance().getUser();
        if (fUsers == null) {
            toast(R.string.user_info_error_info);
            finish();
            return;
        }
        circleTransform = new GlideCircleTransform(this);
        initView();
        showData(fUsers);
    }

    @Override
    protected void initInject() {
        setContentView(R.layout.activity_user_info);
        ButterKnife.bind(this);
    }

    private void initView() {
        mBtnChangeImg.setOnClickListener(this);
        mIvUserImg.setOnClickListener(this);
        mTvName.setOnClickListener(this);
        mBtnBindWeixin.setOnClickListener(this);
        mBtnBindQQ.setOnClickListener(this);
        mBtnBindWeibo.setOnClickListener(this);
        btn_unreg.setOnClickListener(this);
    }

    private void showData(FUsers fUsers) {
        loadIcon(fUsers);
        mTvName.setText(TextUtils.isEmpty(fUsers.getNickName()) ? getString(R.string.user_info_no_name) : fUsers.getUName());
        setThirdBindState(mBtnBindQQ, fUsers.getOpenList(), ThirdUser.OPENTYPE_QQ);
        setThirdBindState(mBtnBindWeibo, fUsers.getOpenList(), ThirdUser.OPENTYPE_WEIBO);
        setThirdBindState(mBtnBindWeixin, fUsers.getOpenList(), ThirdUser.OPENTYPE_WEIXIN);
    }

    private void loadIcon(FUsers fUsers) {
        GlideUtil.getDynamicGlid(this, fUsers.getUIcon(), true).diskCacheStrategy(DiskCacheStrategy.NONE).transform(circleTransform).into(mIvUserImg);
//        new ResultAsyncTask<Void>(){
//            @Override
//            protected Void doInBackground(Void... params) {
//                JLog.e(Glide.getPhotoCacheDir(UserInfoActivity.this).toString());
//                Glide.get(UserInfoActivity.this).clearDiskCache();
//                return null;
//            }
//        }.ex();
    }

    private ThirdUser getThirdUser(List<ThirdUser> list, int type) {
        if (ListUtils.isListValued(list)) {
            for (int i = 0; i < list.size(); i++) {
                ThirdUser tu = list.get(i);
                if (tu != null && tu.getOpenType() == type) {
                    return tu;
                }
            }
        }
        return null;
    }

    private void setThirdBindState(CustomFontTextView tv, ThirdUser user) {
        if (tv == null) {
            return;
        }
        if (user != null && user.isBound()) {
            tv.setText(R.string.user_info_binded);
            tv.setTextColor(ContextCompat.getColor(this, R.color.colorBlack22));
        } else {
            tv.setText(R.string.user_info_unbind);
            tv.setTextColor(ContextCompat.getColor(this, R.color.colorGray98));
        }
        tv.setTag(user);
    }

    private void setThirdBindState(CustomFontTextView tv, List<ThirdUser> list, int type) {
        if (tv == null) {
            return;
        }
        setThirdBindState(tv, getThirdUser(list, type));
    }

    @Override
    public void onClick(View v) {
        JLog.e("click in v=" + v);
        switch (v.getId()) {
            case R.id.btn_change_img:
            case R.id.iv_user_img:
//                if (mPicChoice == null) {
                mPicChoice = new PicChoiceDiaFragment().setType(PicChoiceDiaFragment.TYPE_PIC);
                mPicChoice.setCallBack(this);
//                }
                safeShowDialog(mPicChoice, "changeImg");
                break;
            case R.id.btn_change_name:
//                if (mChangeNameDialog == null) {
                mChangeNameDialog = new AlertEditDialogFragment().setTitleStr(getString(R.string.user_info_change_name_title)).setOkStrRes
                        (R.string.ok).setCancleStrRes(R.string.cancel).setEditHintStrRes(R.string.user_info_edit_hint).setOnViewClick
                        (this).setCancelOut(true);
//                }
                mChangeNameDialog.setEditStr(UserManager.getInstance().getUser().getNickName());
                safeShowDialog(mChangeNameDialog, "changeName");
                break;
            case R.id.btn_bind_weixin:
                bindWeixin();
                break;
            case R.id.btn_bind_qq:
                bindQQ();
                break;
            case R.id.btn_bind_weibo:
                bindWeibo();
                break;
            case R.id.btn_unreg:
                showUnregDialogt();
                break;
        }
    }

    private ConfirmUnregFragment showDiaFragment;
    public static final String SHOW_TAG = "dia_show_fragment";

    private void showUnregDialogt() {
//        if (showDiaFragment == null) {
        showDiaFragment = new ConfirmUnregFragment();
//        }
        showDiaFragment.setCallBack(callBack);
        showDiaFragment.show(getSupportFragmentManager(), SHOW_TAG);
    }

    //Dialog点击回调
    public BaseDialogFragment.ICallBack callBack = new BaseDialogFragment.ICallBack() {
        @Override
        public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
            parseWhat(msg.what);
        }
    };

    /**
     * 切换字体后回调刷新UI
     *
     * @param what
     */
    private void parseWhat(int what) {
        if (what == ShowDiaFragment.LOGINOUT_TAG) {
            SkipUtil.skipToAddUserOperate( this, getOwnerName(),   21, 0, "退出登录", "", "");
            UserManager.getInstance().setUser(this, null);
            UserManager.getInstance().delUserCache(this);
            Intent intent = new Intent(UserInfoActivity.this, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }
    private synchronized void changeImg(String path) {
        if (imgCall != null) {
            imgCall.cancel();
//            return;
        }
        isChangeImg = true;
        ParamsEditor pe = new ParamsEditor();
        pe.put("siteNumber", Constances.SITE_ID);
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        pe.put("userName", UserManager.getInstance().getUser().getPhoneNumber());
        ArrayMap<String, Object> map = pe.getEncryptedParams(UserManager.getInstance().getToken());
        imgCall = NetUtils.getNetAdapter().modifyAvatar(getOwnerName(), map
                , path, new AbsNetCallBack<SingleResult>(SingleResult.class, path) {
                    @Override
                    public void onSuc(SingleResult singleResult) {
                        JLog.e("result is " + singleResult);
                        if (singleResult != null && singleResult.isSuccess()) {
//                            UserManager.getInstance().getUser().setAvatar((String) obj);
                            UserManager.getInstance().getUser().setAvatar(singleResult.getAvatarUrl());
                            UserManager.saveLogin(UserInfoActivity.this);
                            handler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    loadIcon(UserManager.getInstance().getUser());
                                }
                            }, 500);
                            toast("修改成功");
                        } else {
                            toast("修改失败");
                        }
                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg) {
                        super.onError(ex, errorMsg);
                        JLog.e("error code== " + errorMsg);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        isChangeImg = false;
                        JLog.e("call is " + imgCall + "\npath=" + obj + "uimg=" + UserManager.getInstance().getUser().getAvatar());
                    }
                });
        JLog.e("call img " + imgCall);
    }

    private synchronized void changeName(String name) {
        if (isChangeNameing) {
            return;
        }
        isChangeNameing = true;
        ParamsEditor pe = new ParamsEditor();
        pe.put("nickName", name);
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.ModifyName, pe.getEncryptedParams(UserManager.getInstance().getToken())
                , new AbsNetCallBack<SingleResult>(SingleResult.class, name) {
                    @Override
                    public void onSuc(SingleResult singleResult) {
                        if (singleResult != null && singleResult.isSuccess()) {
                            if (obj != null && obj instanceof String) {
                                String n = (String) obj;
                                UserManager.getInstance().getUser().setNickName(n);
                                UserManager.saveLogin(UserInfoActivity.this);
                                mTvName.setText(n);
                            }
                            toast("修改成功");
                        } else {
                            toast("修改失败");
                        }

                    }

                    @Override
                    public void onError(Throwable ex, String errorMsg, int netCode) {
                        super.onError(ex, errorMsg, netCode);
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        isChangeNameing = false;
                    }
                });
    }

    private void bindWeixin() {
        JLog.e("in weixin click");
        bindClick(mBtnBindWeixin, ThirdUser.OPENTYPE_WEIXIN, Wechat.NAME);
    }

    private void bindQQ() {
        bindClick(mBtnBindQQ, ThirdUser.OPENTYPE_QQ, QQ.NAME);
    }

    private void bindWeibo() {
        bindClick(mBtnBindWeibo, ThirdUser.OPENTYPE_WEIBO, SinaWeibo.NAME);
    }

    private ThirdUser getThirdUserFromTag(CustomFontTextView tv) {
        if (tv == null) {
            return null;
        }
        Object obj = tv.getTag();
        if (obj != null && obj instanceof ThirdUser) {
            return (ThirdUser) obj;
        }
        return null;
    }

    private synchronized void bindClick(CustomFontTextView tv, int type, String name) {
        if ( tv == null) {
            return;
        }
        thirdClickTemp = tv;
        ThirdUser user = getThirdUserFromTag(tv);
        if (user == null || !user.isBound()) {
            openType = type;
            thirdLogin(name);
        } else {
            if (user.getOpenType() == UserManager.getInstance().getUser().getBindType()) {
                thirdClickTemp = null;
                String msg = "";
                switch (user.getOpenType()) {
                    case ThirdUser.OPENTYPE_WEIXIN:
                        msg = "当前使用微信登录，不能解绑微信";
                        break;
                    case ThirdUser.OPENTYPE_QQ:
                        msg = "当前使用QQ登录，不能解绑QQ";
                        break;
                    case ThirdUser.OPENTYPE_WEIBO:
                        msg = "当前使用微博登录，不能解绑微博";
                        break;
                }
                Toast.makeText(this, msg, Toast.LENGTH_LONG).show();
            } else {
//                unBindThirdUser();
                showUnBindDialog(type);
            }
        }
    }

    @Override
    public boolean onViewClick(View view, int viewItem, int mode) {
        if (viewItem == AlertDialogFragment.VIEW_ITEM_OK) {
            if ( mChangeNameDialog.getEditStr().length()<2) {
                toast(R.string.user_info_edit);
            } else if (mChangeNameDialog.getEditStr().equals(UserManager.getInstance().getUser().getNickName())) {
                toast(R.string.user_info_change_name_no_changed);
            } else {
                mChangeNameDialog.dismissAllowingStateLoss();
                changeName(mChangeNameDialog.getEditStr());
            }
        }
        return true;
    }

    @Override
    public void onCallBackMsg(BaseDialogFragment fragment, Message msg) {
        if (msg.what == PicChoiceDiaFragment.SHOT_TAG) {
            PictureSelector.create(this).openCamera(PictureMimeType.ofImage()).enableCrop(true).withAspectRatio(4, 3).circleDimmedLayer(true)
                    .freeStyleCropEnabled(false).showCropGrid(false).showCropFrame(false).compress(true)
                    .compressMode(PictureConfig.SYSTEM_COMPRESS_MODE).setOutputCameraPath(PictureFileUtils.CAMERA_PIC_PATH)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        } else if (msg.what == PicChoiceDiaFragment.PIC_TAG) {
            PictureSelector.create(this).openGallery(PictureMimeType.ofImage()).maxSelectNum(1).minSelectNum(1).enableCrop(true)
                    .withAspectRatio(4, 3).circleDimmedLayer(true).freeStyleCropEnabled(false).showCropGrid(false).showCropFrame(false)
                    .compress(true).compressMode(PictureConfig.SYSTEM_COMPRESS_MODE).setOutputCameraPath(PictureFileUtils.CAMERA_PIC_PATH)
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择结果回调
                    List<LocalMedia> selectList = PictureSelector.obtainMultipleResult(data);
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，以取压缩路径为准，因为是先裁剪后压缩的
                    String path = selectList.get(0).getCompressPath();
                    JLog.e("pic path=" + path);
//                    Glide.with(this).load(path).transform(circleTransform).into(mIvUserImg);
                    changeImg(path);
                    break;
            }
        }
    }

    private void showUnBindDialog(int openType) {
        //  if (unbindDialog == null) {
        unbindDialog = new AlertDialogFragment().setLayoutRes(R.layout.fragment_alert_dialog_new);
        unbindDialog.setOnViewInit(new AlertDialogFragment.OnViewInit() {
            @Override
            public void onViewInit(Dialog dialog, Bundle savedInstanceState) {
                View v = (View) dialog.findViewById(R.id.alert_base).getParent();
                JLog.e("base=" + v + "\nback=" + v.getBackground());
                v.setBackgroundColor(Color.TRANSPARENT);
                v = (View) v.getParent();
                JLog.e("base=" + v + "\nback=" + v.getBackground());
                v.setBackgroundColor(Color.TRANSPARENT);
                CustomFontTextView tv = unbindDialog.getMsgView();
                ViewGroup.MarginLayoutParams mlp = (ViewGroup.MarginLayoutParams) tv.getLayoutParams();
                mlp.topMargin = getResources().getDimensionPixelOffset(R.dimen.person_alert_msg_margin_top);
                mlp.bottomMargin = getResources().getDimensionPixelOffset(R.dimen.person_alert_msg_margin_bottom);
                tv.setLayoutParams(mlp);
                tv.setTextColor(Color.BLACK);
                int size = getResources().getDimensionPixelSize(R.dimen.T3);
                JLog.e("will set size " + size);
                tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, size);
                tv.setText(R.string.ensure_unbind);
            }
        });
        unbindDialog.setOnViewClick(new AlertDialogFragment.OnViewClick() {
            @Override
            public boolean onViewClick(View view, int viewItem, int mode) {
                if (viewItem == AlertDialogFragment.VIEW_ITEM_OK) {
                    unBindThirdUser(mode);
                } else if (viewItem == AlertDialogFragment.VIEW_ITEM_CANCLE) {
                    thirdClickTemp = null;
                }
                return true;
            }
        });
        // }
        unbindDialog.setModeTag(openType);
        try {
            unbindDialog.show(getSupportFragmentManager(), "unbind");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void resetThirdBindState(int type, ThirdUser user) {
        switch (type) {
            case ThirdUser.OPENTYPE_QQ:
                setThirdBindState(mBtnBindQQ, user);
                break;
            case ThirdUser.OPENTYPE_WEIBO:
                setThirdBindState(mBtnBindWeibo, user);
                break;
            case ThirdUser.OPENTYPE_WEIXIN:
                setThirdBindState(mBtnBindWeixin, user);
                break;
        }
    }

    private void bindThirdUser(PlatformDb db) {
        if (db == null) {
            thirdClickTemp = null;
            return;
        }
//        ArrayMap<String, Object> map = new ArrayMap<>();
//        StringBuffer sb = new StringBuffer();
//        map.put("openId", db.getUserId());
//        sb.append(db.getUserId());
//        map.put("openType", openType);
//        sb.append(openType);
//        map.put("userId", UserManager.getInstance().getUser().getUserId());
//        sb.append(UserManager.getInstance().getUser().getUserId());
//        String str = HmacSHA256Utils.digest(db.getToken(), sb.toString());
//        JLog.e("secret key=" + db.getToken() + "  content=" + sb.toString() + "\nresult=" + str);
//        map.put("token", str);

        ParamsEditor pe = new ParamsEditor();
        pe.put("openId", db.getUserId());
        pe.put("openType", openType);
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.BindThir, pe.getEncryptedParams(UserManager.getInstance().getToken())
                , new AbsNetCallBack<SingleResult>(SingleResult.class) {
                    @Override
                    public void onSuc(SingleResult singleResult) {
                        if (singleResult != null && singleResult.isSuccess()) {
                            ThirdUser tu = new ThirdUser();
                            tu.setBound(true);
                            tu.setOpenType(openType);
                            addThirdBinded(tu);
                            if (thirdClickTemp != null) {
                                setThirdBindState(thirdClickTemp, tu);
                            } else {
                                resetThirdBindState(openType, tu);
                            }
                        }
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        thirdClickTemp = null;
                    }
                });
    }

    private void unBindThirdUser(int openType) {
        ParamsEditor pe = new ParamsEditor();
        pe.put("openType", openType);
        pe.put("userId", UserManager.getInstance().getUser().getUserId());
        NetUtils.getNetAdapter().postGetSingle(getOwnerName(), DMethods.UNBindThir, pe.getEncryptedParams(UserManager.getInstance().getToken())
                , new AbsNetCallBack<SingleResult>(SingleResult.class, openType) {
                    @Override
                    public void onSuc(SingleResult singleResult) {
                        if (singleResult != null && singleResult.isSuccess()) {
                            if (removeThirdBind(int1)) {
                                setThirdBindState(thirdClickTemp, null);
                            }
                        }
                    }

                    @Override
                    public void onEnd() {
                        super.onEnd();
                        thirdClickTemp = null;
                    }
                });
    }

    private void thirdLogin(String name) {
        Platform p = ShareSDK.getPlatform(name);
        p.setPlatformActionListener(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                PlatformDb db = platform.getDb();
                if (db != null) {
                    JLog.e(db.exportData());
//                    Message msg = handler.obtainMessage(WHAT_LOGIN_THIRD, db);
//                    handler.sendMessage(msg);
                    bindThirdUser(db);
                } else {
                    JLog.e("login failed the platform db is null");
                }
                JLog.e("map=" + hashMap);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                JLog.e("login get error");
                if (throwable != null) {
                    throwable.printStackTrace();
                }
                thirdClickTemp = null;
            }

            @Override
            public void onCancel(Platform platform, int i) {
                thirdClickTemp = null;
            }
        });

        p.authorize();
//        p.showUser(null);
    }

    private void addThirdBinded(ThirdUser user) {
        if (user == null) {
            return;
        }
        FUsers fUsers = UserManager.getInstance().getUser();
        List<ThirdUser> list = fUsers.getOpenList();
        if (list == null) {
            list = new ArrayList<>();
            list.add(user);
            fUsers.setOpenList(list);
            UserManager.saveLogin(this);
        } else {
            if (list.size() == 0) {
                list.add(user);
                UserManager.saveLogin(this);
            } else {
                boolean isContain = false;
                for (ThirdUser tu :
                        list) {
                    if (tu.getOpenType() == user.getOpenType()) {
                        isContain = true;
                        if (tu.isBound() != user.isBound()) {
                            tu.setBound(user.isBound());
                            UserManager.saveLogin(this);
                        }
                        break;
                    }
                }
                if (!isContain) {
                    list.add(user);
                    UserManager.saveLogin(this);
                }
            }
        }
    }

    private boolean removeThirdBind(int openType) {
        FUsers fUsers = UserManager.getInstance().getUser();
        if (ListUtils.isListValued(fUsers.getOpenList())) {
            List<ThirdUser> list = fUsers.getOpenList();
            for (int i = 0; i < list.size(); i++) {
                if (list.get(i).getOpenType() == openType) {
                    list.remove(i);
                    UserManager.saveLogin(this);
                    return true;
                }
            }
        }
        return false;
    }
}
